<template>
  <div class="app-container">
    <el-card class="filter-container">
      <div>
        <i class="el-icon-search" />
        <span>筛选搜索</span>
        <div class="filter-btn">
          <el-button
            icon="el-icon-search"
            type="primary"
            size="small"
            @click="handleSearchList()"
          >
            查询
          </el-button>
          <el-button
            icon="el-icon-setting"
            size="small"
            @click="handleResetSearch()"
          >
            重置
          </el-button>

          <el-button
            class="btn-add"
            type="success"
            size="mini"
            icon="el-icon-plus"
            @click="() => { newUserFormVisible = true; newUserForm = {} }"
          >
            添加
          </el-button>
        </div>

      </div>
      <div style="margin-top: 25px">
        <el-form :inline="true" :model="listQuery" size="small">
          <el-row>
            <el-col :sm="12" :lg="6">
              <el-form-item label="账号：">
                <el-input v-model="listQuery.name" placeholder="账号" />
              </el-form-item>
            </el-col>

            <el-col :sm="12" :lg="6">
              <el-form-item label="状态：">
                <el-select v-model="listQuery.status" placeholder="全部" clearable>
                  <el-option
                    v-for="item in statusOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>

          </el-row>

        </el-form>
      </div>
    </el-card>

    <el-card class="table-container">
      <el-table
        v-loading="listLoading"
        element-loading-text="加载中"
        :data="list"
        fit
      >
        <el-table-column align="center" width="200" label="登录账号">
          <template slot-scope="scope">
            <span>{{ scope.row.account }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="账号昵称">
          <template slot-scope="scope">
            <span>{{ scope.row.nickname }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="头像">
          <template slot-scope="scope">
            <el-image :src="scope.row.avatar" fit="contain" />
          </template>
        </el-table-column>

        <el-table-column align="center" label="邮箱">
          <template slot-scope="scope">
            <span>{{ scope.row.email }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="性别">
          <template slot-scope="scope">
            <svg-icon v-if="scope.row.gender" icon-class="female" />
            <svg-icon v-else icon-class="male" />
          </template>
        </el-table-column>

        <el-table-column align="center" label="状态">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status | statusTypeFilter">{{ scope.row.status | statusTextFilter }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column align="center" label="备注">
          <template slot-scope="scope">
            <span>{{ scope.row.remark }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" class-name="operate-cell">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              @click="allocUserGroup(scope.row)"
            >分配用户组
            </el-button>

            <el-divider direction="vertical" />

            <el-button
              v-if="scope.row.status === 0"
              size="mini"
              @click="enable(scope.row)"
            >启用
            </el-button>
            <el-button
              v-else
              size="mini"
              type="warning"
              @click="disable(scope.row)"
            >禁用
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageLimit" @pagination="getList" />
    </el-card>

    <el-dialog
      title="新增用户"
      :visible.sync="newUserFormVisible"
      center
      width="30%"
    >
      <el-form
        ref="newUserForm"
        :rules="newUserFormRules"
        :model="newUserForm"
      >
        <el-form-item label="账号：" prop="account">
          <el-input
            v-model="newUserForm.account"
            placeholder="账号"
          />
        </el-form-item>
        <el-form-item label="密码：" prop="password">
          <el-input
            v-model="newUserForm.password"
            type="password"
            placeholder="密码"
          />
        </el-form-item>
        <el-form-item
          label="确认密码："
          prop="confirmPassword"
        >
          <el-input
            v-model="newUserForm.confirmPassword"
            type="password"
            placeholder="确认密码"
          />
        </el-form-item>
        <el-form-item
          label="备注："
        >
          <el-input
            v-model="newUserForm.remark"
            type="password"
            placeholder="备注"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="newUserFormVisible = false">取 消</el-button>
        <el-button :loading="loading" type="primary" @click="handleSaveUser">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="分配用户组"
      :visible.sync="updateUserGroupVisible"
      width="30%"
    >
      <el-select
        v-model="userGroupIds"
        multiple
        filterable
        size="small"
        reserve-keyword
        placeholder="请输入用户组名"
        style="width: 80%"
      >
        <el-option
          v-for="item in userGroupList"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="updateUserGroupVisible = false">取 消</el-button>
        <el-button type="primary" :loading="loading" size="small" @click="handleUpdateUserGroupConfirm()">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>

import {
  getPageList,
  create,
  updateUserGroups,
  updateStatus
} from '@/api/system/user'

import {
  getList as getUserGroupList,
  getListByUser as getUserGroupListByUser
} from '@/api/system/user-group'

import Pagination from '@/components/Pagination'

const defaultListQuery = {
  pageNum: 1,
  pageLimit: 10,
  sorts: '-createTime'
}

const statusMap = {
  1: {
    type: 'success',
    text: '启用'
  },
  0: {
    type: 'warning',
    text: '禁用'
  }
}

export default {
  components: { Pagination },
  filters: {
    statusTypeFilter(status) {
      return statusMap[status].type
    },
    statusTextFilter(status) {
      return statusMap[status].text
    }
  },
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.newUserForm.confirmPassword !== '') {
          this.$refs.newUserForm.validateField('confirmPassword')
        }
        callback()
      }
    }
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.newUserForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }

    return {
      newUserForm: {},
      newUserFormVisible: false,
      newUserFormRules: {
        password: [
          { validator: validatePass, trigger: 'blur' }
        ],
        confirmPassword: [
          { validator: validatePass2, trigger: 'blur' }
        ]
      },

      listQuery: Object.assign({}, defaultListQuery),
      list: [],
      total: 0,

      statusOptions: [{
        value: 1,
        label: '启用'
      }, {
        value: 0,
        label: '禁用'
      }],

      listLoading: true,
      loading: false,

      userGroupListInit: false,
      userGroupIds: [],
      userGroupList: [],
      updateUserGroupVisible: false

    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      getPageList(this.listQuery).then(response => {
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleSearchList() {
      this.listQuery.pageNum = 1
      this.getList()
    },
    handleResetSearch() {
      this.listQuery = Object.assign({}, defaultListQuery)
    },
    allocUserGroup(row) {
      this.currentUserId = row.id

      if (!this.userGroupListInit) {
        this.getUserGroupList()
      }

      this.getUserGroupListByUser(this.currentUserId)
      this.updateUserGroupVisible = true
    },
    handleUpdateUserGroupConfirm() {
      this.$confirm('确认分配用户组?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateUserGroups(this.currentUserId, this.userGroupIds).then(_ => {
          this.$message.success('分配用户组成功！')
          this.updateUserGroupVisible = false
          this.getList()
        })
      })
    },
    getUserGroupListByUser(userId) {
      getUserGroupListByUser(userId).then(res => {
        const userGroupIds = []
        res.data.map(item => {
          userGroupIds.push(item.id)
        })

        this.userGroupIds = userGroupIds
      })
    },
    getUserGroupList(query) {
      getUserGroupList().then(res => {
        this.userGroupList = res.data
        this.userGroupListInit = true
      })
    },
    enable(row) {
      this.$confirm('是否要启用账户?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.updateStatus(row.id, 1)
      })
    },
    disable(row) {
      this.$confirm('是否要禁用账户?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.updateStatus(row.id, 0)
      })
    },
    updateStatus(id, status) {
      updateStatus(id, status).then(response => {
        this.$message({
          message: '修改成功',
          type: 'success',
          duration: 1000
        })

        this.getList()
      })
    },
    handleSaveUser() {
      this.$refs.newUserForm.validate(valid => {
        if (valid) {
          this.$confirm('是否提交数据', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            // 对密码进行加密
            const params = Object.assign({}, this.newUserForm)
            params.password = this.$md5(params.password)
            params.confirmPassword = this.$md5(params.confirmPassword)

            create(params).then(_ => {
              this.$message.success('新建用户成功，如需登录请分配合适的用户组！')
              this.newUserFormVisible = false
            })
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style scoped>
  .el-image{
    width: 40px;
    height: 40px;
  }
</style>
